package com.qianyitian.hope2.analyzer.gaokao;

import com.alibaba.fastjson.JSON;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@RestController
public class GaokaoController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    File fileWen = new File("db/2021-tidang-wenke.json");
    File fileLi = new File("db/2021-tidang-like.json");
    List<TouDang> likeList = null;
    List<TouDang> wenkeList = null;

    public GaokaoController() {
        try {
            String s = Files.asCharSource(fileWen, Charset.forName("UTF-8")).read();
            wenkeList = JSON.parseArray(s, TouDang.class);

            s = Files.asCharSource(fileLi, Charset.forName("UTF-8")).read();
            likeList = JSON.parseArray(s, TouDang.class);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    @CrossOrigin
    @RequestMapping(value = "/gaokao", method = RequestMethod.POST)
    public List<TouDang> startAnalyzeInBackgroud(@RequestParam String type, @RequestParam String college, @RequestParam String mayjor,
                                                 @RequestParam String lowScore, @RequestParam String highScore,
                                                 @RequestParam String lowPosition, @RequestParam String highPosition) {
        int lowS = 10;
        int highS = 750;
        int lowP = 99999990;
        int highP = 0;


        try {
            lowS = Integer.valueOf(lowScore);
        } catch (RuntimeException e) {
        }

        try {
            highS = Integer.valueOf(highScore);
        } catch (RuntimeException e) {
        }

        try {
            lowP = Integer.valueOf(lowPosition);
        } catch (RuntimeException e) {
        }

        try {
            highP = Integer.valueOf(highPosition);
        } catch (RuntimeException e) {
        }

        List<TouDang> base = null;
        if (type.equals("wenke")) {
            base = wenkeList;
        } else {
            base = likeList;
        }

        String[] majors = mayjor.split(" ");


        List<TouDang> collect = new ArrayList<>();
        for (TouDang item : base) {
            boolean ok = item.getCollege().contains(college) && checkMajor(item, majors) &&
                    item.getScore() >= lowS && item.getScore() <= highS &&
                    item.getPosition() <= lowP && item.getPosition() >= highP;
            if (ok) {
                collect.add(item);
            }
        }
        return collect;
    }

    private boolean checkMajor(TouDang item, String[] mayjors) {
        for (String major : mayjors) {
            if (item.getMajor().contains(major)) {
                return true;
            }
        }
        return false;
    }
}
